package at.fhj.itm11.forum.gui;

import java.util.concurrent.TimeUnit;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebElement;

import at.fhj.itm11.forum.api.ApiLookupNames;
import at.fhj.itm11.forum.gui.pages.AddPostPage;
import at.fhj.itm11.forum.gui.pages.ShowPostPage;
import at.fhj.itm11.forum.service.TestHelperService;

public class US07 extends AbstractGUITest {

	private static final String TEXT = "Dies ist mein Beitrag";
	private static final String TITLE = "Mein Beitrag";
	private TestHelperService dbHelper;

	@Before
	public void additionalSetUp() {
		dbHelper = lookupBean(ApiLookupNames.TEST_HELPER,
				TestHelperService.class);

		dbHelper.cleanDB();
		dbHelper.createDemoData();
	}

	@Test
	public void createPostWithTextOnly() {
		login();
		navigateToShowPostPage(1);
		AddPostPage addPostPage = navigateToAddPostPage();
		addPostPage.titleTextField.sendKeys(TITLE);
		addPostPage.textTextArea.sendKeys(TEXT);
		addPostPage.btnAddPost.click();

		WebElement title = driver.findElement(By
				.xpath("//span[contains(text(), '" + TITLE + "')]"));
		WebElement text = driver
				.findElement(By
						.xpath("//table[contains(@id, 'postTable')]/tbody/tr[1]//td/div/div[2]"));

		Assert.assertEquals("Title does not match", TITLE, title.getText());
		Assert.assertEquals("Text does not match", TEXT, text.getText());
	}

	@Test(expected = NoSuchElementException.class)
	public void shouldNotCreatePost() {
		// element can not be located, so a shorter timeout is in place
		driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);

		login();
		navigateToShowPostPage(1);
		AddPostPage addPostPage = navigateToAddPostPage();
		addPostPage.titleTextField.sendKeys(TITLE);
		addPostPage.textTextArea.sendKeys(TEXT);
		addPostPage.btnReset.click();

		driver.findElement(By
				.xpath("//span[contains(text(), '" + TITLE + "')]"));
		driver.findElement(By
				.xpath("//table[contains(@id, 'postTable')]/tbody/tr[1]//td/div/div[2]"));
	}

	@Test(expected = NoSuchElementException.class)
	public void shouldNotBeAbleToPost() {
		// element can not be located, so a shorter timeout is in place
		driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);

		ShowPostPage showPostPage = navigateToShowPostPage(1);
		showPostPage.addPostLink.click();
	}
}
